package com.golden.procedure.activiti.client;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class activitiClientAPI {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    /**
     * 启动流程
     */
    public String startWorkflow(String processKey, String userId, String businessKey, Map<String, Object> variables) {

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey, businessKey, variables);
        //ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey);
        String processInstanceId = processInstance.getId();
        logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{processKey, businessKey, processInstanceId, variables});
        return processInstanceId;

    }

    /**
     * 查询待办任务
     */
    public List<String> findTodoTasks(String processKey, String taskDefinitionKey, String userId) {
        List<String> results = new ArrayList<String>();
        List<Task> tasks = new ArrayList<Task>();

        // 根据当前人的ID查询
        //List<Task> todoList = taskService.createTaskQuery().processDefinitionKey(processKey).taskId(taskId).taskAssignee(userId).active().list();
        List<Task> todoList = taskService.createTaskQuery().processDefinitionKey(processKey).taskDefinitionKey(taskDefinitionKey).active().list();

        // 根据当前人未签收的任务
        //List<Task> unsignedTasks = taskService.createTaskQuery().processDefinitionKey(processKey).taskId(taskId).taskCandidateUser(userId).active().list();
        List<Task> unsignedTasks = taskService.createTaskQuery().processDefinitionKey(processKey).taskDefinitionKey(taskDefinitionKey).active().list();

        // 合并
        tasks.addAll(todoList);
        tasks.addAll(unsignedTasks);

        // 根据流程的业务ID查询实体并关联
        for (Task task : tasks) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            String businessKey = processInstance.getBusinessKey();
            results.add(businessKey);
        }
        return results;
    }

    /**
     * 完成任务
     * @param taskId
     * @param variables
     */
    public void complete(String taskId, Map<String, Object> variables) {
        taskService.complete(taskId, variables);
    }
}
